package com.ziyucoding.springboot.labs.redislike.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;

/**
 * 返回结果
 *
 * @author ziyucoding
 * @date 2023-02-07
 **/
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL) // 只序列化非空值
public class CommonResponse<T> {

    private Integer code;

    private String msg;

    private T data;

    protected CommonResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 请求成功，无数据返回
     *
     * @return CommonResponse<T>
     */
    public static <T> CommonResponse<T> createForSuccess() {
        return new CommonResponse<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getName(), null);
    }

    /**
     * 请求成功，并返回响应数据
     *
     * @param data
     * @return CommonResponse<T>
     */
    public static <T> CommonResponse<T> createForSuccess(T data) {
        return new CommonResponse<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getName(), data);
    }

    /**
     * 请求错误，默认错误信息
     *
     * @return CommonResponse<T>
     */
    public static <T> CommonResponse<T> createForError() {
        return new CommonResponse<>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getName(), null);
    }

    /**
     * 请求错误，指定错误信息
     *
     * @param message
     * @return CommonResponse<T>
     */
    public static <T> CommonResponse<T> createForError(String message) {
        return new CommonResponse<>(ResponseCode.ERROR.getCode(), message, null);
    }

    /**
     * 请求错误，指定错误码和错误信息
     *
     * @param code
     * @param message
     * @return CommonResponse<T>
     */
    public static <T> CommonResponse<T> createForError(Integer code, String message) {
        return new CommonResponse<>(code, message, null);
    }

    @JsonIgnore
    public boolean isSuccess() {
        return this.code == ResponseCode.SUCCESS.getCode();
    }

}
